var sum = 0;
var dialogData;
var taocan;

//进入页面的 时候的计算
function countAll(){
	var length = $('input[name="checkbox"]:checked').length;
	$('#allnum').html(length);
	countSum();
	formatUseLife();
}

//将年限重新格式化一下
function formatUseLife(){
	var idList = $('input[name="shoppingCartId"]');
	var lifeList = $('input[name="useLife"]');
	for(var i=0;i<lifeList.length;i++){
		var id = idList[i].value;
		var life = lifeList[i].value;
		if(life == "-1"){
			$('#plusYear'+id).attr("value","∞");
		}else if(life == "0"){
			$('#plusYear'+id).attr("value","20天");
		}
		
	}
}

//sum 总计金额 
function countSum(){
	var checkboxList = $("input[name='checkbox']");
	var priceList = $('.price_line');
	var sum = 0.00;
	for(var i=0;i<priceList.length;i++){
		_sum = $('.price_line')[i].innerHTML;
		if(checkboxList[i].checked == true)	sum += parseFloat(_sum);
	}
	$('#allsum').html(parseFloat(sum).toFixed(2));
}

//单选  以及相关的总计
function cancleOther(){
	var checkbox = $("input[name='checkbox']");
	$('input[name="checkboxAll"]').prop("checked",checkbox.length == $("input[name='checkbox']:checked").length ? true : false);
	
	var length = $('input[name="checkbox"]:checked').length;
	$('#allnum').html(length);
	countSum();
}

//计算  userNumber 基数    price  价格      userYear  年限  allsum 总计
function count(id){
	var userNumber = $('#userNumber'+id).val();
	var price = $('#price'+id).val();
	var userYear = $('#userYear'+id).val();
	var num = $('#proMealNum'+id)[0].innerHTML;
	var localPrice = $('#localUseYear'+id).val();
	
	var _userNumer = $('#plusUserNum'+id).val();
	var _userYear = $('#plusYear'+id).val();
	
	if(parseInt(localPrice) == 0 && _userYear == '20天'){
		 $('#proMealPrice'+id).val('0.00');
		 $('#proMealPrice'+id).html('0.00');
		 return;
	}else if(parseInt(_userYear) == 0){
		$('#proMealPrice'+id).val('0.00');
		 $('#proMealPrice'+id).html('0.00');
		 return;
	}
	
	if(parseInt(userYear) == 0 || userYear == "-1") userYear = 1;
	if(_userYear == "∞") _userYear = 1;
	
	var _price = parseFloat(_userNumer / userNumber * price * (_userYear / userYear) * num ).toFixed(2) ;
	
	$('#proMealPrice'+id).val(_price);
	$('#proMealPrice'+id).html(_price);
	
}

//年限加号减号触发事件
function plusOrMinusYearNum(code,addend,e,id){
	var addnum = $('#'+e).val();
	var localPrice = $('#localUseYear'+id).val();
	
	if(addnum == '∞'){
		BSTYUN.dialog.warn('年限已最大！');
		return;
	}
	if(code=='plus'){
		if(addnum == '20天'){
			addnum = 0;
			addend == 1;
		}
		addnum = parseInt(addnum) + parseInt(addend);
	}
	else if(code=='minus'){
		if(addnum == '20天'){
			BSTYUN.dialog.warn('此条记录加入购物车时为试用，则最小年限为20天！');
			$('#'+e).val('20天');
			
			count(id);
			return;
		}
		addnum = parseInt(addnum) - parseInt(addend);
	}
	
	if(localPrice == '0' && parseInt(addnum) < 0 ) {
		BSTYUN.dialog.warn('此条记录加入购物车时为试用，则最小年限为20天！');
		$('#'+e).val('20天');
		
		count(id);
		return;
	}else if(parseInt(addnum) < 1 ){
		BSTYUN.dialog.warn('不能再减啦！最小年限不能为0年！');
		$('#'+e).val(1);
	}else $('#'+e).val(addnum);
	
	rangeValid('userYear',e,id);
	
	count(id);
	
	countSum();
	
}

//用户数量 加号减号触发事件
function plusOrMinusUserNum(code,addend,e,id){
	var addend = $('#'+addend).val();
	var addnum = $('#'+e).val();
	if(code=='plus') addnum = parseInt(addnum) + parseInt(addend);
	else if(code=='minus') addnum = parseInt(addnum) - parseInt(addend);
	
	if(parseInt(addnum) < 10) {
		
		BSTYUN.dialog.warn('不能再减啦！最小用户数量不能为0！');
		$('#'+e).val(10);
	}
	else $('#'+e).val(addnum);
	
	rangeValid('maxUser',e,id);
	
	count(id);
	
	countSum();
}

//数量 加号减号触发事件
function plusOrMinusProMealNum(code,addend,e,id){
	var addnum = $('#'+e).val();
	if(code=='plus') addnum = parseInt(addnum) + parseInt(addend);
	else if(code=='minus') addnum = parseInt(addnum) - parseInt(addend);
	
	if(parseInt(addnum) < 0) {}//alert("不能小于0");
	else $('#'+e).val(addnum);
	
	countProduct(id);
}

//数量 变化 导致价格变化
function countProduct(id){
	var userNumber = $('#userNumber'+id).val();
	var price = $('#price'+id).val();
	var userYear = $('#userYear'+id).val();
	var _userYear = $('#plusYear'+id).val();
	var _userNumer = $('#plusUserNum'+id).val();
	var num = $('#proMealNum'+id)[0].innerHTML;
	
	if(parseInt(userYear) == 0) userYear = 1;
	if(parseInt(_userYear) == 0) _userYear = 1;
	
	var _price = parseFloat(_userNumer / userNumber * price * (_userYear / userYear)  * num).toFixed(2) ;
	$('#proMealPrice'+id).val(_price);
	$('#proMealPrice'+id).html(_price);
}

//验证是否处于最大最小值范围  值 类型 修改的字段 
function rangeValid(type,e,id){
	if(type == "maxUser"){
		var userNumber = $('#maxUser'+id).val();
		var _userNumber = $('#plusUserNum'+id).val();
		if(parseInt(_userNumber) > parseInt(userNumber)) {
			BSTYUN.dialog.warn('不能再加啦！最大数量为'+userNumber+'！');
			$('#plusUserNum'+id).val(userNumber);
		}
	}else if(type == "userYear"){
		var userYear = $('#maxYear'+id).val();
		var _userYear = $('#plusYear'+id).val();
		if(parseInt(_userYear) > parseInt(userYear)){
			BSTYUN.dialog.warn('不能再加啦！最大年限为'+userYear+'年！');
			$('#plusYear'+id).val(userYear);
		}
	}
}

//年限验证
function yearNumValid(para,e,id){
	var num = $('#'+e).val();
	if(num == '') BSTYUN.dialog.warn('请输入数字，不能为空！');
	var reg = new RegExp(/^[0-9]*$/); 
	if(reg.exec(num) == null){
		BSTYUN.dialog.warn('请输入整数！');
		$('#'+e).val(0);
	}else{
		rangeValid('userYear',e,id);
		count(id);
	}
}

//用户数量验证userNumber,maxUser, ,'maxUser'+${sc.shoppingCartId},'userYear'+${sc.shoppingCartId}
function userNumValid(para,e,id){
	var num = $('#'+e).val();
	if(num == '') BSTYUN.dialog.warn('请输入数字，不能为空！');
	var _num = num / para;
	var reg = new RegExp(/^[0-9]*$/); 
	if(reg.exec(_num) == null){
		BSTYUN.dialog.warn('请输入10的整倍数！');
		$('#'+e).val(parseInt(parseInt(num)/10)*10);
	}else{
		rangeValid('maxUser',e,id);
		count(id);
	}
}

//数量验证
function proMealNumValid(para,e,id){
	var num = $('#'+e).val();
	var reg = new RegExp(/^[0-9]*$/); 
	if(num == '') BSTYUN.dialog.warn('请输入数字，不能为空！');
	if(reg.exec(num) == null){
		BSTYUN.dialog.warn('请输入整数！');
		$('#'+e).val(parseInt(num));
	}
}

//全选 以及相关的总计
$(function(){
	var $input = $(".cart_checkbox").find("input");
	var $checkall = $(".checkboxAll");
	$checkall.on("click",function(){
		var $this = $(this);
		if(!$this.prop("checked")){
			$checkall.eq(0).prop("checked",false);
			$checkall.eq(1).prop("checked",false);
			$input.each(function(){
				var _this = $(this);
				_this.prop("checked",false);
			});
			$('#allnum').html(0);
			$('#allsum').html(0.00);
			
		}else{
			$checkall.eq(0).prop("checked",true);
			$checkall.eq(1).prop("checked",true);
			$input.each(function(){
				var _this = $(this);
				_this.prop("checked",true);
			});
			
			var length = $("#shoppingCartTable").children("tbody").children("tr").length;
			$('#allnum').html(length);
			
			countSum();
		}
	});
	
	
	$cart = null;
	var $shopping_button = $(".shopping_cart");
	var	$shop = $(".right_textcon");
	var $buy_button = $(".buy");
	
	//点击购买时检查该用户是否试用过
	$('.buy').on('click',function(){
		var useYear = $('.dropbox').eq(1).find('.dropbox_value').attr('data-value'),
			proMealId = $('#proMealId').val(),
			productId = $('#productId').val(),
//			proId = $('#productId').val(),
			userNum = $('.dropbox').eq(0).find('.dropbox_value').attr('data-value'),
			price = parseFloat($('#price').html()).toFixed(2),
			pmStatus = $('#pmStatus').val(),
			pageNum = $('#pageNum').val(),
			shoppingCartId = $('#shoppingCartId').val(),
			proMealName = $('#proMealName').val(),
			version = $('#version').val(),
			requestURI = $('#requestURI').val(),
			loginUserEmail = $('#loginUserEmail').val(),
			loginUserIsYun = $('#loginUserIsYun').val(),
			loginUserParentId = $('#loginUserParentId').val(),
			loginUserRoleId = $('#loginUserRoleId').val();

		$.ajax({
			type : "POST",
			url : "/common/checkLogin",
			async : false,
			dataType: 'json',
			success:function(data) {
				if(data) {
					if(pmStatus == 1) {
						//单个产品购买,判断有无套餐
						$.ajax({
							type:"POST",
							url:"/buy/haveMealByUserId",
							async:false,
							dataType:"json",
							success:function(data,response){
								if(data){
									var orderVoList = data.orderVoList;
									var proList = data.proList;
									if(orderVoList.length > 0){  
										for(var i=0;i<orderVoList.length;i++){
											var overTime = orderVoList[i].overTime;
											overTime = new Date(overTime);
//											overTime = toDate(overTime,"yyyy-MM-dd");
											orderVoList[i].overTime = overTime;
										}
										setProName(proList,orderVoList);
										calculate(orderVoList,useYear,userNum,price);
										showMealList($buy_button,orderVoList,shoppingCartId,useYear,userNum,price,2,proMealId,version,proMealName,productId);
									}else{
										BSTYUN.dialog.warn("请先购买套餐！（产品依托于套餐使用，请先购买MC云办公标准版！）");
									}
									
								}
							}
						})
					}else {
//						if(loginUserIsYun == '0' || loginUserParentId != ""){
						if(loginUserRoleId == '0' ){
							BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
							return;
//						}else if(loginUserParentId == ""){
						}else if(loginUserRoleId == "1"){
							$.ajax({
								type:"POST",
								url:"/buy/haveMealsNum",
								async:false,
								dataType:"json",
								success:function(data,response){
									if(data.orderVoList){
										var ol = data.orderVoList;
										var _uy;
										var isBFree=false,haveB=false,haveF=false;
										for(var i=0;i<ol.length;i++){
											var o = ol[i];
											if(o.mealId == 1) {
												haveB=true;
												if(o.isFree == 1) isBFree=true;
											}
										}
										
										if(proMealId == '1'){
											if(haveB){
												if(isBFree && useYear == '0'){
													BSTYUN.dialog.warn("您已经免费试用过该套餐！");
												}else{
													BSTYUN.dialog.warn("您已经购买过该套餐！");
												}
											}else{
												location.href="/dredge/"+proMealId+"/"+useYear+"/"+userNum+"/"+price+"/0/"+pageNum+"/"+shoppingCartId+"/"+proMealName+"/"+version+"/"+productId;
											}
										}
									}else{
										BSTYUN.dialog.warn("网络异常，请求失败，请重试！");
									}
								}
							})
							//所有的都能立即购买
//							location.href="/dredge/"+proMealId+"/"+useYear+"/"+userNum+"/"+price+"/0/"+pageNum+"/"+shoppingCartId+"/"+proMealName+"/"+version+"/"+productId;
						}else if(loginUserRoleId == '2'){
							location.href="/dredge/"+proMealId+"/"+useYear+"/"+userNum+"/"+price+"/0/"+pageNum+"/"+shoppingCartId+"/"+proMealName+"/"+version+"/"+productId;
						}
						
					}
					
				}else {
					location.href = "/user/login?returnUrl="+requestURI;
				}
			}
		})
	})
	
	//点击加入购物车时检查该用户是否登录或者选择的是否是试用产品
	$shopping_button.on('click',function(){
		var useLife = $('.dropbox').eq(1).find('.dropbox_value').attr('data-value'),
			proMealId = $('#proMealId').val(),
			userNum = $('.dropbox').eq(0).find('.dropbox_value').attr('data-value'),
			proMealPrice = parseFloat($('#price').html()).toFixed(2),
			pmStatus = $('#pmStatus').val(),
			requestURI = $('#requestURI').val(),
			loginUserEmail = $('#loginUserEmail').val(),
			loginUserIsYun = $('#loginUserIsYun').val(),
			loginUserParentId = $('#loginUserParentId').val(),
			loginUserRoleId = $('#loginUserRoleId').val();

		$.ajax({
			type : "POST",
			url : "/common/checkLogin",
			async : false,
			dataType: 'json',
			success:function(data) {
				if(data) {
					if(pmStatus == 1) {
						$.ajax({
							type : "POST",
							url : "/buy/shoppingCart/add",
							async : false,
							data : {
								proMealId : proMealId,
								pmStatus : pmStatus,
								useLife : useLife,
								userNum : userNum,
								proMealPrice : proMealPrice
							},
							dataType: 'json',
							success:function(data){
								if(data.isSuccess) {
									showAddDialog($shopping_button,$cart,$shop,data.sumNum,data.sumPrice);
								}else {
									BSTYUN.dialog.warn("加入购物车失败，请重新加入购物车！！");
								}
							}
						})
					}else {
//						if(loginUserIsYun == '0' || loginUserParentId != ""){
						if(loginUserRoleId == '0'){
							BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
							return;
//						}else if(loginUserParentId == ""){
						}else if(loginUserRoleId == "1"){
							$.ajax({
								type:"POST",
								url:"/buy/haveMealsNum",
								async:false,
								dataType:"json",
								success:function(data,response){
									if(data.orderVoList){
										var ol = data.orderVoList;
										
										var isBFree=false,haveB=false,haveF=false;
										for(var i=0;i<ol.length;i++){
											var o = ol[i];
											if(o.mealId == 1) {
												haveB=true;
												if(o.isFree == 1) isBFree=true;
											}
										}
										
										if(proMealId == '1'){
											if(haveB){
												if(isBFree && useLife == '0'){
													BSTYUN.dialog.warn("您已经免费试用过该套餐！");
												}else{
													BSTYUN.dialog.warn("您已经购买过该套餐！");
												}
											}else{
												$.ajax({
													type : "POST",
													url : "/buy/shoppingCart/add",
													async : false,
													data : {
														proMealId : proMealId,
														pmStatus : pmStatus,
														useLife : useLife,
														userNum : userNum,
														proMealPrice : proMealPrice
													},
													dataType: 'json',
													success:function(data){
														if(data.isSuccess) {
															showAddDialog($shopping_button,$cart,$shop,data.sumNum,data.sumPrice);
														}else {
															BSTYUN.dialog.warn("加入购物车失败，请重新加入购物车！！");
														}
													}
												})
											}
										}
									}else{
										BSTYUN.dialog.warn("网络异常，请求失败，请重试！");
									}
								}
							})
							//所有的都可以加入购物车中
							/*$.ajax({
								type : "POST",
								url : "/buy/shoppingCart/add",
								async : false,
								data : {
									proMealId : proMealId,
									pmStatus : pmStatus,
									useLife : useLife,
									userNum : userNum,
									proMealPrice : proMealPrice
								},
								dataType: 'json',
								success:function(data){
									if(data.isSuccess) {
										showAddDialog($shopping_button,$cart,$shop,data.sumNum,data.sumPrice);
									}else {
										BSTYUN.dialog.warn("加入购物车失败，请重新加入购物车！！");
									}
								}
							})*/
						}else if(loginUserRoleId == '2'){
							$.ajax({
								type : "POST",
								url : "/buy/shoppingCart/add",
								async : false,
								data : {
									proMealId : proMealId,
									pmStatus : pmStatus,
									useLife : useLife,
									userNum : userNum,
									proMealPrice : proMealPrice
								},
								dataType: 'json',
								success:function(data){
									if(data.isSuccess) {
										showAddDialog($shopping_button,$cart,$shop,data.sumNum,data.sumPrice);
									}else {
										BSTYUN.dialog.warn("加入购物车失败，请重新加入购物车！！");
									}
								}
							})
						}
						
					}
				}else {
					location.href = "/user/login?returnUrl="+requestURI;
				}
			}
		})
	})
	

	
	//个人应用服务中的免费购买==========================修改
	$('#freeBuy').on('click',function(){
		
		var useYear = 0,
			proMealId = $('#proMealId').val(),
			userNum = 0,
			price = 0,
			pmStatus = $('#pmStatus').val(),
			pageNum = $('#pageNum').val(),
			shoppingCartId = $('#shoppingCartId').val(),
			proMealName = $('#proMealName').val(),
			version = $('#version').val(),
			requestURI = $('#requestURI').val(),
			productId = proMealId;
		
		$.ajax({
			type : "POST",
			url : "/common/checkLogin",
			async : false,
			dataType: 'json',
			success:function(data) {
				if(data) {
					//单个产品购买,判断有无套餐
					$.ajax({
						type:"POST",
						url:"/buy/haveMealByUserId",
						async:false,
						dataType:"json",
						success:function(data,response){
							if(data){
								var orderVoList = data.orderVoList;
								var proList = data.proList;
								if(orderVoList.length > 0){
									for(var i=0;i<orderVoList.length;i++){
										var overTime = orderVoList[i].overTime;
										overTime = new Date(overTime);
//										overTime = toDate(overTime,"yyyy-MM-dd");
										orderVoList[i].overTime = overTime;
									}
									setProName(proList,orderVoList);
									calculate(orderVoList,useYear,userNum,price);
									showMealList($buy_button,orderVoList,shoppingCartId,useYear,userNum,price,1,proMealId,version,proMealName,productId);
									
								}else{
									BSTYUN.dialog.warn("请先购买套餐！（产品依托于套餐使用，请先购买MC云办公标准版或MC云办公私有云！）");
								}
							}
						}
					})
				}else {
					location.href = "/user/login?returnUrl="+requestURI;
				}
			}
		})
	})
});

//微调距离tools
function resieFit(x,y){
	return {
		offsetx: x-35,
		offsety: y+27
	}
}

//计算使用年限和使用人数以及价格
function calculate(orderVoList,useYear,userNum,price){
	//每年每用户价格
	var _onePrice = price/userNum/useYear;
//	list[i].aUseLife+'</td><td>'+list[i].aEndTime+'</td><td>'+list[i].aPrice+'</td><td>'+list[i].aSumPrice
	
	for(var i=0;i<orderVoList.length;i++){
		
		var _toTime = 0,_tDay = 0;
		
		var order = orderVoList[i];
		var o_year = order.useLife;
		var o_usernum = order.userNum; 
		var o_overTime = order.overTime;
		var newDate = new Date();
		order.overTime = formatDate(o_overTime,"yyyy-MM-dd");
		
		_toTime = calculateMonth(newDate,o_overTime,'returnDate');
		
		var d = '';
		if(getYear(_toTime).year != 0) d = getYear(_toTime).year + '年' ;
		if(getYear(_toTime).month != 0) d += getYear(_toTime).month + '月';
		if(getYear(_toTime).day != 0) d += getYear(_toTime).day + '天';
		
		order.aOverTime = d;
		
		//使用人数 
		if(userNum < o_usernum) order.aUserNum = userNum ;
		else order.aUserNum = o_usernum;

		//使用年限
		if(useYear == '-1'){
			//产品暂时没有永久
		}else if(useYear == '0'){
			//免费试用
			order.aPrice = 0.00;
			order.aSumPrice = 0.00;
			if(o_year == '-1'){
				order.aUseLife = '20天';
				order.aEndTime = formatDate(AddDays(newDate,20,'day'),"yyyy-MM-dd");
			}else if(o_year == '0'){//加入试用套餐
				_toTime = calculateMonth(newDate,o_overTime,'returnDate');
				
				var d = '';
				if(getYear(_toTime).year != 0) d = getYear(_toTime).year + '年' ;
				if(getYear(_toTime).month != 0) d += getYear(_toTime).month + '月';
				if(getYear(_toTime).day != 0) d += getYear(_toTime).day + '天';
				
				order.aUseLife = d;
				order.aEndTime = formatDate(o_overTime,"yyyy-MM-dd");
			}else{
				_toTime = calculateMonth(newDate,o_overTime,'returnDate');
				_tDay = getYear(_toTime).year * 360 + getYear(_toTime).month * 30 + getYear(_toTime).day * 1;
				
				if(_tDay > 20) {
					d = '20天';
					order.aEndTime = formatDate(AddDays(newDate,20,'day'),"yyyy-MM-dd");
				}else {
					d = _tDay + '天';
					order.aEndTime = formatDate(AddDays(newDate,_tDay,'day'),"yyyy-MM-dd");
				}
				order.aUseLife = d;
				order.aPrice = 0.00;
				order.aSumPrice = 0.00;
			}
		}else{
			//购买
			if(o_year == '-1'){//加入永久套餐
				order.aUseLife = useYear+'年';
				order.aEndTime = formatDate(AddDays(newDate,useYear,'year'),"yyyy-MM-dd");
				order.aPrice = _onePrice;
				order.aSumPrice = _onePrice * useYear * order.aUserNum;
			}else if(o_year == '0'){//加入试用套餐
				_toTime = calculateMonth(newDate,o_overTime,'returnDate');
				
				var d = '';
				if(getYear(_toTime).year != 0) d = getYear(_toTime).year + '年' ;
				if(getYear(_toTime).month != 0) d += getYear(_toTime).month + '月';
				if(getYear(_toTime).day != 0) d += getYear(_toTime).day + '天';
				
				order.aUseLife = d;
				order.aEndTime = formatDate(o_overTime,"yyyy-MM-dd");
				order.aPrice = 0.00;
				order.aSumPrice = 0.00;
			}else{//加入标准套餐
				_toTime = calculateMonth(newDate,o_overTime,'returnDate');
				_toMonth = calculateMonth(newDate,o_overTime,'returnMonth');
				_tDay = getYear(_toTime).year * 360 + getYear(_toTime).month * 30 + getYear(_toTime).day * 1;
				
				var d = '';
				if(getYear(_toTime).year != 0) d = getYear(_toTime).year + '年' ;
				if(getYear(_toTime).month != 0) d += getYear(_toTime).month + '月';
				if(getYear(_toTime).day != 0) d += getYear(_toTime).day + '天';
				
				if(Number(_tDay) > useYear * 360) {
					d = useYear + '年';
					order.aEndTime = formatDate(AddDays(newDate,useYear,'year'),"yyyy-MM-dd");
					order.aUseLife = d;
					order.aPrice = _onePrice;
					order.aSumPrice = _onePrice * useYear * order.aUserNum;
				}else {
					order.aEndTime = formatDate(AddDays(newDate,_tDay,'day'),"yyyy-MM-dd");
					order.aUseLife = d;
					order.aPrice = _onePrice;
					order.aSumPrice = _onePrice / 12 * _toMonth * order.aUserNum;
				}
				
				
			}
		}
		
	}
}

//弹出框去支付  version,proMealName,
function gotoPay(shoppingCartId,mealId,useYear,userNum,proMealPrice,proMealNum,userId,proMealName,version,productId,orderId){
	
	$.ajax({
		type:"POST",
		url:"/buy/selectOrderByIsFree",
		async:false,
		data:{
			userId:userId,
			mealId:mealId,
			newProId:productId,
			proMealPrice:proMealPrice 
		},
		success:function(data){
			if(!data){
				BSTYUN.dialog.warn("该套餐内已包含该产品，如需继续使用，请到订单管理续费！");
			}else{
				var sc = {
					shoppingCartId:shoppingCartId,
					proMealId:mealId,
					proMealName:proMealName,
					useLife:useYear,
					userNum:userNum,
					proMealPrice:proMealPrice,
					proMealNum:proMealNum,
					version:version,
					userId:userId 
				}
				_sc = JSON.stringify(sc);
				$.ajax({
					type:"POST",
					url:"/buy/cartToCheck",
					async:false,
					data:{
						_sc:_sc,
						productId:productId,
						orderId:orderId
					},
					success:function(data){
						if(data){
							dialogData=null;
							location.href="/buy/checkOrders";
						}
					}
				})
			}
		}
	})
}

//购物车  查看详情 按钮
function gotoDetail(orderId){
	window.open("/consume/order/order_detail?orderId="+orderId);
}

//弹出套餐列表
function showMealList(btn,list,shoppingCartId,useYear,userNum,price,flg,proMealId,version,proMealName,productId){
	var _op = 0.00;
	var cyear;//当前选择产品的的年限  展现
	var showCyear;
	if(useYear ==0){
		showCyear = '20天';
	}else{
		showCyear = useYear;
	}
	
	var endTime;//当前购买产品截止日期
	var nowDate = new Date();
	if(useYear == 0) {
		cyear = '20天';
		_op = 0.00;
		endTime = AddDays(nowDate,20,'day');
		endTime = formatDate(endTime,"yyyy-MM-dd");
	}else{
		cyear = useYear;
		endTime = AddDays(nowDate,cyear,'year');
		endTime = formatDate(endTime,"yyyy-MM-dd");
		_op = price/cyear/userNum;
	}
	
	var dialog = null,
    html = '',
    callback = null;
	html = '<div class="product_box">';
	html += '<ul class="nav_title cle"><li>订单编号</li><li>套餐名称</li><li>公司名称</li><li>域名</li><li class="special_li">子产品</li><li style="width:60px">使用年限</li><li style="width:60px">使用人数</li></ul>';
	for(var i=0;i<list.length;i++){
		var _list = list[i];
//		var showYear;
		var useLife = _list.useLife;
//		var aUseYear = _list.aUseYear;
//		showYear = aUseYear;
		
		if(useLife == 0) useLife = '20天';
		else if(useLife == "-1") useLife = "∞";
		
		html += '<dl><dt class="product_inforbox"><ul class="cle">';
		html += '<li class="choose_pro"><input type="radio" name="choose_pro"></li>';
		
		html += '<input type="hidden"  name ="orderId" id="orderId'+list[i].orderId+'" value="'+list[i].orderId+'" />';
		html += '<input type="hidden"  name ="mealId" id="mealId'+list[i].orderId+'" value="'+list[i].mealId+'" />';
		html += '<input type="hidden"  name ="userId" id="userId'+list[i].orderId+'" value="'+list[i].userId+'" />';
		html += '<input type="hidden"  name ="proId" id="proId'+list[i].orderId+'" value="'+proMealId+'" />';
		html += '<input type="hidden"  name ="price" id="price'+list[i].orderId+'" value="'+price+'" />';
		html += '<input type="hidden"  name ="flg" id="flg'+list[i].orderId+'" value="'+flg+'" />';
		
		html += '<li><span>'+list[i].orderNum+'</span></li>';
		html += '<li><span>'+list[i].mealName+'</span></li>';
		html += '<li><span>'+list[i].belongCompanyName+'</span></li>';
		html += '<li><span>'+list[i].companyDomainName+'</span></li>';
		html += '<li class="special_li"><span>'+list[i].proNames+'</span></li><li style="width:60px"><span>'+useLife+'</span></li><li style="width:60px"><span>'+list[i].userNum+'</span></li>';
		html += '<li class="lookfor_detail"><a href="javascript:void(0);" target="_blank"  onclick="gotoDetail('+list[i].orderId+')">查看详情</a></li>';
		html += '</ul></dt>';   
		html += '<dd class="product_detail"><div><h4>您所选套餐为'+list[i].mealName+'，最大使用人数为'+list[i].userNum+'人，截止当前时间，使用年限剩余'+list[i].aOverTime+'</h4>';
		html += '<dl><dt>选择该套餐后，您所购买的产品：</dt><table><tbody><tr><td></td><td>产品名称</td><td>用户数量</td><td>使用年限</td><td>截止日期</td><td>单价</td><td>金额</td></tr>';
        html += '<tr><td>当前购买</td><td>'+proMealName+'</td><td>'+userNum+'</td><td>'+showCyear+'</td><td>'+endTime+'</td><td>'+_op+'</td><td>'+price+'</td></tr>';
        html += '<tr><td>实际购买</td><td>'+proMealName+'</td><td>'+list[i].aUserNum+'</td><td>'+list[i].aUseLife+'</td><td>'+list[i].aEndTime+'</td><td>'+list[i].aPrice+'</td><td>'+parseFloat(list[i].aSumPrice).toFixed(2)+'</td></tr></tbody></table></dl>';
		html += '<p style="color:red">确定请点击“去支付”按钮。';
		html += '<a href="javascript:void(0);" class="goto_pay" onclick="gotoPay('+shoppingCartId+','+list[i].mealId+','+useYear+','+userNum+','+list[i].aSumPrice+',1,'+list[i].userId+',\''+proMealName+'\',\''+version+'\',\''+productId+'\',\''+list[i].orderId+'\')">去支付</a></p></div></dd>';
	}
	
	html += '<div class="page_control"><span></span></div></div>';
	dialog = BSTYUN.dialog.creat({
	  id:'gouwuche',
	  title: '',
	  content:html,
	  init:function(){
	    var $box = $('.product_box'),
	        $inforbox = $box.find('.product_inforbox'),
	        $radio = $box.find('.choose_pro input'),
	        $detail = $box.find('.product_detail'),
	        $page = $box.find('.page_control span'),
	        element = 1,  //分子，当前页数,默认第一页
	        denominator = Math.ceil($inforbox.size()/3),//分母，总页数
	        page_html = '';
	    /*调整样式，使li垂直居中*/
	    
	    /*分页功能,默认显示第一条*/
	    page_html = '<span><em class="element">1</em>/<em class="denominator">'+denominator+'</em>页，共<em class="denominator">'+denominator+'</em>页，</span><span><a href="javascript:void(0);" data-flag="index">首页</a> <a href="javascript:void(0);" data-flag="prev">上一页</a> <a href="javascript:void(0);" data-flag="next">下一页</a></span>';
	    $page.html(page_html);
	    showPage(1);
	    var $ele = $page.find('.element');
	    /*绑定单选按钮事件,默认选中第一条*/
	    $radio.on('click', function(event) {
	      var $this = $(this);
	      $detail.hide();
	      $this.parents('dt').next('dd').show();
	    });
	    $radio.eq(0).trigger('click');
	    /*绑定分页按钮*/
	    $page.on('click', 'a', function(event) {
	      var $this = $(this),
	          flag = $this.attr('data-flag');
	      switch(flag){
	        case 'index':
	          $ele.text(1);
	          showPage(1);
	          break;
	        case 'next':
	          var index = parseInt($ele.text()),
	              next = null;
	          if (index < denominator) {
	            next = index+1;
	            showPage(next);
	            $ele.text(next);
	          }
	          break;
	        case 'prev':
	          var index = parseInt($ele.text()),
	              prev = null;
	          if (index > 1) {
	            prev = index-1;
	            showPage(prev);
	            $ele.text(prev);
	          }
	          break;
	      }
	    });
	    /*显示第几页*/
	    function showPage(count){// 0,1,2  3,4,5  ,6,7,8
	      var count = count,
	          range = [count*3-3,count*3-1];
	      $inforbox.each(function(index, val) {
	         var $this = $(this);
	         if (range[0] <= index && index <= range[1]) {
	           $this.show();
	         }else{
	            $this.hide().next('dd').hide();
	         }
	      });
	      /*原先选中的状态还是为选中*/
	      $radio.each(function(index, val) {
	        var $this = $(this),
	            $prarent = $this.parents('.product_inforbox'),
	            index = $inforbox.index($prarent);
	          if (range[0] <= index && index <= range[1]) {
	             if ($this.prop('checked')) {
	              $this.parents('dt').next('dd').show();
	             }
	          };
	      });
	    }
	  }
	});
	dialog.size('1045px','480px')
	dialog.position('50%','50%')//重新定位
	
}

//显示加入购物车弹出框
function showAddDialog($this,$cart,$shop,num,total){
	//设置购物车内容
	var cart_box = '<em>'+$shop.find('dt').eq(0).text()+'</em> 已成功加入购物车<br/>购物车中有<font color="red">'+num+'</font>件商品，共计<font color="red">￥'+(parseFloat(total).toFixed(2))+'</font>';
	//设定弹出框的位置。
	var offset = $this.offset(),
		offsetx = offset.left,
		offsety = offset.top,
		resizefit = resieFit(offsetx,offsety);
	if ($cart !== null) {
		return false;
	};
	$cart = $.dialog({
	    content: '加载中...',
	    left: resizefit.offsetx+'px',
	    top: resizefit.offsety+'px',
	    content: cart_box,
	    drag: false,
	    button:[{
	    	name: '查看购物车',
	    	callback:function(){
	    		location.href = '/buy/shoppingCart';
	    	},
	    	focus: true
	    },{
	    	name: '继续购买',
	    	callback:function(){
				location.href = '/mall';
	    	}
	    }],
	    close:function(){
	    	$cart = null;
	    }
	});
	//删除标题内容
	$($cart.title()).remove();
}

//匹配套餐内的产品Name
function  setProName(proList,orderVoList){
	for(var i=0;i<orderVoList.length;i++){
		var proId = orderVoList[i].proIds;
		var arr = "";
		if(proId != null && proId.indexOf('|')<0){
			arr = proId;
		}else{
			if(proId != null)
				arr = proId.split('|');
		}
		var proName = [];
		for(var j=0;j<arr.length;j++){
			var pro_id = arr[j];
			var pro_name = "";
			for(var k=0;k<proList.length;k++){
				if(pro_id == proList[k].productId){
					pro_name = proList[k].productName;
					break;
				}
			}
			proName.push(pro_name);
		}
		orderVoList[i].proNames = proName;
	}
}

//购物车中  确认订单时  先判断是否有套餐
function checkOrders(shoppingCartId){
	var _useYear = $('#plusYear'+shoppingCartId).val(); 
	var useYear = _useYear;
	if(_useYear == '∞') useYear = -1;
	if(_useYear == '20天') useYear = 0;
	var userNum = $('#plusUserNum'+shoppingCartId).val();
	var proMealId = $('#proMealId'+shoppingCartId).val();
	var price = $('#proMealPrice'+shoppingCartId)[0].innerHTML;
	var $submit_btn = $(".submit_btn"+shoppingCartId);
	var pmType = $('#pmType'+shoppingCartId).val();
	var pageNum = $('#pageNum').val();
	var shoppingCartId = $('#shoppingCartId'+shoppingCartId).val();
	var proMealName = $('#proMealName'+shoppingCartId)[0].innerHTML;
	var version = $('#version'+shoppingCartId).val();
	var companyDomainName = $('#companyDomainName').val();
	
	if(userNum == "0" || _useYear == "0"){
		return BSTYUN.dialog.warn("请选择正确的使用人数和使用年限！");
	}
	
	if(pmType == 1 || pmType == 2){
		location.href="/dredge/"+proMealId+"/"+useYear+"/"+userNum+"/"+price+"/0/"+pageNum+"/"+shoppingCartId+"/"+proMealName+"/"+version+"/0";
	}else if(pmType == 3 || pmType == 4 || pmType == 5){
		productId = proMealId;
		//判断有无套餐
		$.ajax({
			type:"POST",
			url:"/buy/haveMealByUserId",
			async:false,
			dataType:"json",
			success:function(data,response){
				if(data){
					var orderVoList = data.orderVoList;
					var proList = data.proList;
					if(orderVoList.length > 0){
						for(var i=0;i<orderVoList.length;i++){
							var overTime = orderVoList[i].overTime;
							overTime = new Date(overTime);
//							overTime = toDate(overTime,"yyyy-MM-dd");
							orderVoList[i].overTime = overTime;
						}
						setProName(proList,orderVoList);
						
						calculate(orderVoList,useYear,userNum,price);
						showMealList($submit_btn,orderVoList,shoppingCartId,useYear,userNum,price,0,proMealId,version,proMealName,productId);
						
					}else{
						BSTYUN.dialog.warn("请先购买套餐！（产品依托于套餐使用，请先购买MC云办公标准版！）");
					}
					
				}
			}
		})
	}
}

//购物车  单条删除
function deleteShoppingCart(shoppingCartId,userId){
	var shoppingCartId = shoppingCartId;
	BSTYUN.dialog.confirm('确定删除该条数据？',function(){
		$.ajax({
			type:"GET",
			url:"/buy/deleteShoppingCartByShoppingCartId/" + shoppingCartId,
			async:false,
			success:function(response,data){
				if(data == "success"){
					$('#sc'+shoppingCartId).remove();
					countAll();
					resetTable();
					BSTYUN.dialog.ok("删除成功！");
				}
			}
		})
	});
}

//购物车  批量删除
function deleteShoppingCarts(){
	var _shoppingCartList = "";
	var checkboxList = $("input[name='checkbox']");
	var shoppingCartId = $("input[name='shoppingCartId']");
	var userId = $("input[name='userId']");
	var shoppingCartList = $('input[name="shoppingCartId"]');
	for(var i=0;i<shoppingCartList.length;i++){
		if(checkboxList[i].checked == true) {
			_shoppingCartList += ",";
			_shoppingCartList += shoppingCartId[i].value;
		}
	}
	_shoppingCartList = _shoppingCartList.substr(1);
	
	if(_shoppingCartList == "") return BSTYUN.dialog.warn("请选择一条记录！");
	BSTYUN.dialog.confirm('确定批量删除这些数据？',function(){
		$.ajax({
			type:"GET",
			url:"/buy/deleteShoppingCartsByShoppingCartId/" + _shoppingCartList,
			async:false,
			success:function(response,data){
				if(data == "success"){
					
					var scList = _shoppingCartList.split(",");
					for(var i=0;i<scList.length;i++){
						$('#sc'+scList[i]).remove();
					}
					countAll();
					resetTable();
					BSTYUN.dialog.ok("批量删除成功！");
				}
			}
		})
	});
}

//重置table
function resetTable(){
	var shoppingCartIds = $("input[name='shoppingCartId']");
	if(shoppingCartIds.length == 0){
		var $checkall = $(".checkboxAll");
		$checkall.eq(0).prop("checked",false);
		$checkall.eq(1).prop("checked",false);
		var $tbody = $("#shoppingCartTable tbody");
		$tr = '<tr><td colspan="8">暂无数据，请添加过商品后再查看！</td></tr>';
		$tbody.append($tr);
	}
}

function getYear(str){
	var reg = /\d+/g,
		result = str.match(reg);
	return {
		year: result[0],
		month: result[1],
		day: result[2]
	}
}